package com.food.service.impl;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.food.mapper.AdminMapper;
import com.food.mapper.UsersMapper;
import com.food.pojo.Codes;
import com.food.pojo.Foods;
import com.food.pojo.Users;

import com.food.service.UsersService;

import com.food.util.DateUtil;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import javax.xml.ws.Action;
import java.util.*;

@Service
public class UsersServiceImpl extends ServiceImpl<UsersMapper, Users> implements UsersService {

    @Value("${auth.url}")
    private String url;

    @Value("${minio.endpoint}")
    private String endpoint;

    @Autowired
    UsersMapper usersMapper;
    @Override
    public String getUserToken(String code) {

        //向微信请求openid

        String appid = "wx994fb3fdf10acf8a";
        String secret = "1fea05d8102edd98e56012141fca80d6";
        //发送请求

        RestTemplate restTemplate = new RestTemplate();
        // 拼接sql
        String loginUrl = "https://api.weixin.qq.com/sns/jscode2session?appid=" + appid +
                "&secret=" + secret + "&js_code=" + code + "&grant_type=authorization_code";

        String forObject = restTemplate.getForObject(loginUrl, String.class);
//        String forObject="{\"session_key\":\"gJWz5MqyHuujOrWlISgEAA==\",\"openid\":\"oqKWI5SysePRqzhNGA4Ihbck2VbY2\",\"unionid\":\"ouGAk6VT1BH3NlhfqIZn1vp6gEqk\"}";

        Codes codes = JSON.parseObject(forObject, Codes.class);

        //查找是否在数据库中注册过

        assert codes != null;
        Users users = usersMapper.selectOne(new LambdaQueryWrapper<Users>().eq(Users::getOpenid, codes.getOpenid()));
        if(users== null){
            users = new Users();
            users.setUserName("微信用户");
            users.setUserPassword("111111");
            users.setOpenid(codes.getOpenid());
            users.setUserSex("男");
            users.setUserIntroduce("写点啥...");
            users.setUserRegTime(DateUtil.getTime());

            usersMapper.insert(users);
        }

        String getTokenUrl=url+"/auth/oauth/token";

        MultiValueMap<String, String> paramsMap = new LinkedMultiValueMap<>();
        paramsMap.put("grant_type", Collections.singletonList("password"));
        paramsMap.put("client_id", Collections.singletonList("WebApp"));
        paramsMap.put("client_secret", Collections.singletonList("WebApp"));
        paramsMap.put("username", Collections.singletonList("{\"openid\":\""+ users.getOpenid()+"\",\"password\":\""+ users.getUserPassword()+"\",\"authType\":\"password\"}"));
        JSONObject response = restTemplate.postForObject(getTokenUrl, paramsMap, JSONObject.class);
        String access_token =(String)response.get("access_token");
        return access_token;
    }

    /**
     * 获得用户信息
     * @param userId
     */
    @Override
    public Users getUsers(Integer userId) {
        Users users = usersMapper.selectById(userId);
        users.setUserPassword(null);
        users.setOpenid(null);
        return users;
    }

    /**
     * 修改用户信息
     * @param userId
     * @param userName
     * @param userSex
     * @param userIntroduce
     * @param userAvatar
     * @param userBackground
     * @return
     */
    @Override
    public Boolean updataUsers(Integer userId, String userName, String userSex, String userIntroduce, String userAvatar, String userBackground) {
      //查询用户数据
        Users users = usersMapper.selectById(userId);
        users.setUserName(userName);
        users.setUserSex(userSex);
        users.setUserIntroduce(userIntroduce);
        users.setUserAvatar(userAvatar);
        users.setUserBackground(userBackground);
        //修改用户数据
        int numberOfRows= usersMapper.updateById(users);
        if(numberOfRows>0){
            return true;
        }else{
            return false;
        }
    }

    /**
     * 按姓名分页查找用户
     * @param pageParam
     * @param userNameVo
     * @return
     */
    @Override
    public IPage<Users> selectPage(Page<Object> pageParam, String userNameVo) {
        IPage<Users> pageModel = baseMapper.selectPage(pageParam, userNameVo);
        return pageModel;
    }

}
